<template>
  <div class="record-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>档案记录管理</span>
          <el-button type="primary" @click="handleAdd" v-if="['admin', 'teacher'].includes(userStore.roleCode)">
            <el-icon><Plus /></el-icon>
            新增记录
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="记录类型">
          <el-select
            v-model="queryForm.recordType"
            placeholder="请选择类型"
            clearable
            @clear="handleQuery"
          >
            <el-option label="奖励记录" :value="1" />
            <el-option label="惩罚记录" :value="2" />
            <el-option label="学籍异动" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="studentId" label="学生ID" width="100" />
        <el-table-column prop="recordType" label="记录类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getRecordTypeTag(row.recordType)">
              {{ getRecordTypeText(row.recordType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="记录内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right" v-if="['admin', 'teacher'].includes(userStore.roleCode)">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button link type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)" v-if="userStore.roleCode === 'admin'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.current"
          v-model:page-size="queryForm.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuery"
          @current-change="handleQuery"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="90px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学生ID" prop="studentId">
              <el-input-number 
                v-model="form.studentId" 
                :min="1" 
                style="width: 100%" 
                :disabled="isView"
                controls-position="right"
                placeholder="请输入学生ID"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="记录类型" prop="recordType">
              <el-select 
                v-model="form.recordType" 
                placeholder="请选择类型" 
                style="width: 100%" 
                :disabled="isView"
              >
                <template #prefix>
                  <el-icon><DocumentCopy /></el-icon>
                </template>
                <el-option label="奖励记录" :value="1">
                  <el-tag type="success" size="small">奖励记录</el-tag>
                </el-option>
                <el-option label="惩罚记录" :value="2">
                  <el-tag type="danger" size="small">惩罚记录</el-tag>
                </el-option>
                <el-option label="学籍异动" :value="3">
                  <el-tag type="warning" size="small">学籍异动</el-tag>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="记录内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="8"
            placeholder="请输入详细的记录内容..."
            :disabled="isView"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" size="large">
            <el-icon><Close /></el-icon>
            {{ isView ? '关闭' : '取消' }}
          </el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading" v-if="!isView" size="large">
            <el-icon><Check /></el-icon>
            {{ form.id ? '保存' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Refresh, DocumentCopy, Check, Close } from '@element-plus/icons-vue'
import { getRecordPage, addRecord, updateRecord, deleteRecord, type StudentRecord } from '@/api/record'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

// 查询表单
const queryForm = reactive({
  current: 1,
  size: 10,
  recordType: undefined as number | undefined
})

// 表格数据
const tableData = ref<StudentRecord[]>([])
const total = ref(0)
const loading = ref(false)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增记录')
const isView = ref(false)
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
const form = reactive<StudentRecord>({
  studentId: 0,
  recordType: 1,
  content: ''
})

// 表单验证规则
const rules: FormRules = {
  studentId: [
    { required: true, message: '请输入学生ID', trigger: 'blur' }
  ],
  recordType: [
    { required: true, message: '请选择记录类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入记录内容', trigger: 'blur' },
    { min: 10, max: 1000, message: '记录内容长度在 10 到 1000 个字符', trigger: 'blur' }
  ]
}

// 记录类型文本
const getRecordTypeText = (type: number) => {
  const map: Record<number, string> = {
    1: '奖励记录',
    2: '惩罚记录',
    3: '学籍异动'
  }
  return map[type] || '未知'
}

// 记录类型标签
const getRecordTypeTag = (type: number) => {
  const map: Record<number, string> = {
    1: 'success',
    2: 'danger',
    3: 'warning'
  }
  return map[type] || ''
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const data = await getRecordPage(queryForm)
    tableData.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('获取档案记录列表失败', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryForm.current = 1
  getList()
}

// 重置
const handleReset = () => {
  queryForm.recordType = undefined
  handleQuery()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增记录'
  isView.value = false
  dialogVisible.value = true
}

// 查看
const handleView = (row: StudentRecord) => {
  dialogTitle.value = '查看记录'
  isView.value = true
  Object.assign(form, row)
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: StudentRecord) => {
  dialogTitle.value = '编辑记录'
  isView.value = false
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: StudentRecord) => {
  try {
    await ElMessageBox.confirm('确定要删除该记录吗？', '提示', {
      type: 'warning'
    })
    await deleteRecord(row.id!)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败', error)
    }
  }
}

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (form.id) {
          await updateRecord(form)
          ElMessage.success('更新成功')
        } else {
          await addRecord(form)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交失败', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    studentId: 0,
    recordType: 1,
    content: ''
  })
  delete form.id
  isView.value = false
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.record-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-input__prefix) {
  display: flex;
  align-items: center;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-select-dropdown__item) {
  display: flex;
  align-items: center;
  
  .el-tag {
    min-width: 80px;
    justify-content: center;
  }
}
</style>

